package com.demo.springmvc.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request,
                             javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        // 检查 session
        HttpSession session = request.getSession();
        String username = (String)session.getAttribute("user");
        if (username != null) {
            // 如果已经登录，放行
            return true;
        }
        // 没有登录，就跳转到登录页面
        request.getRequestDispatcher("WEB-INF/views/login.jsp").forward(request,response);
        return false;
    }

    @Override
    public void postHandle(javax.servlet.http.HttpServletRequest request,
                           javax.servlet.http.HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception {

    }

    @Override
    public void afterCompletion(javax.servlet.http.HttpServletRequest request,
                                javax.servlet.http.HttpServletResponse response, Object handler, Exception ex)
        throws Exception {

    }
}
